package cn.wen233.orderconsumer.api;

import cn.wen233.common.api.R;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * 使用RestTemplate进行服务间的调用
 *
 * @author wenei
 * @date 2021-06-05 14:53
 */
@RestController
@RequestMapping("/orders")
public class OrderTemplateApi {

    private final RestTemplate restTemplate = new RestTemplate();

    private final DiscoveryClient discoveryClient;

    public OrderTemplateApi(DiscoveryClient discoveryClient) {
        this.discoveryClient = discoveryClient;
    }

    @GetMapping("/1")
    public R<?> getOrder() {
        List<ServiceInstance> instances = discoveryClient.getInstances("order-service");
        ServiceInstance instanceInfo = instances.get(0);
        String ip = instanceInfo.getHost();
        int port = instanceInfo.getPort();
        String url = "http://" + ip + ":" + port + "/orders/" + 1;
        return R.success(restTemplate.getForObject(url, R.class));
    }
}
